package api

import (
	"pan/common/exception"
)

type FastDownloadRequest struct {
	Owner    string
	Dir      string
	Filename string
	SavedDir string
}

func FastDownloadApi(tokenid string, req *FastDownloadRequest, callback *DownloadCallback) error {
	download := &FastDownload{
		Request:  req,
		Tokenid:  tokenid,
		Callback: callback,
	}
	return download.Download()
}

type FastDownload struct {
	Request  *FastDownloadRequest
	Tokenid  string
	Callback *DownloadCallback
}

func (f *FastDownload) Download() error {
	dirRsp, err := DirApi(f.Tokenid, &DirRequest{
		Dir:   f.Request.Dir,
		Owner: f.Request.Owner,
	})

	if err != nil {
		return err
	}
	if dirRsp.Files == nil || len(dirRsp.Files) == 0 {
		return exception.NewExpectError("not found any files")
	}

	var fileDocid string
	for _, file := range dirRsp.Files {
		if file.Name == f.Request.Filename {
			fileDocid = file.Docid
		}
	}
	if fileDocid == "" {
		return exception.NewExpectError("the file named %s was not found", f.Request.Filename)
	}
	return f.doDownload(fileDocid)
}

func (f *FastDownload) doDownload(fileDocid string) error {
	req := &DownloadRequest{
		Docid:    fileDocid,
		UseHttps: true,
	}
	err := DownloadApi(f.Request.SavedDir, f.Tokenid, req, f.Callback)
	if err != nil {
		return err
	}
	return nil
}
